<?php
namespace app\admin\controller;
use app\common\controller\Admin;
use app\common\logic\CategoryLogic;
use app\common\logic\TypeLogic;
use app\common\logic\CatTypeLogic;
use app\common\model\Type;


use app\common\model\CatType as Model;

class Category extends Admin
{
//    public function test(){
//        $list = Model::all();
//        foreach ($list as $item){
//            $type = Type::get($item->type_id);
//            $item->type_title = $type->title;
//            $item->isUpdate()->save();
//        }
//    }

    /**
     * @desc 如果不是ajax，进入首页。如果是ajax就返回数据咯
     * @return mixed|string
     *
     */
    public function index()
    {
        $rule=[
            'moduleid|类别归属'=>'require',
            'parentid|父级id'=>'require',
        ];
        
        $logic = new CategoryLogic();
        
        $params = paramForm();
        $params['paginate'] = true;
        $params['size'] = 10;
       
        $params['parentid'] = isset($params['parentid'])?$params['parentid']:0;
        
        
        $this->validate($params,$rule);
        
        if(\think\Request::instance()->isAjax()){
           
            $parentid = $params['parentid'];
            if(isset($params['title'])){
                unset($params['parentid']);
                $params['title'] = array('like','%'.$params['title'].'%');
            }
            
            $categoryList = $logic->getList($params);
            
            $level = $logic->getLevel($parentid);
            if($level==3&&$params['moduleid']==1){
                foreach ($categoryList as $cat){
                    $cat['types'] = $logic->getTypes($cat->id);
                }
            }
            success($categoryList);
        }else{
            
            $typeName = $logic->getTypeName($params['moduleid']);
            $this->assign('typeName', $typeName);
            $this->assign('moduleid', $params['moduleid']);
            $this->assign('parentid',$params['parentid']);
    
            $level = $logic->getLevel($params['parentid']);
            $this->assign('level',$level);
            
            return $this->fetch();
        
        }
        
    }
    
//    public function getTabelData(){
//        $logic = new CategoryLogic();
//        $rt = $logic->getTabelData(3);
//        if($rt['code']){
//            success($rt['data']);
//        }else{
//            error($rt['msg']);
//        }
//    }

    public function getFoldList(){
        
        $len = paramForm('len')?paramForm('len'):1;
        $logic = new CategoryLogic();
        $cats = $logic->getFoldList($len);
        
        if($cats['code']){
            success($cats['data']);
        }else{
            error('获取失败');
        }

        
    }
    
    public function add(){
    
        $rule=[
            'moduleid|类别归属'=>'require',
            'parentid|父级id'=>'require',
        ];
    
        $logic = new CategoryLogic();
        $params = paramForm();
        
        $this->validate($params,$rule);
        $typeName = $logic->getTypeName($params['moduleid']);
        $this->assign('typeName', $typeName);
        
        $this->assign('moduleid', $params['moduleid']);
        $this->assign('parentid',$params['parentid']);
    
        $level = $logic->getLevel($params['parentid']);
        $this->assign('level',$level);
        
        //循环获取所有的类别信息
//        $typeLogic = new TypeLogic();
//        $types = $typeLogic->getFoldList();
//        $this->assign('types',$types);
        
        return $this->fetch();
        
    }

    public function save(){
    
        $rule = [
            'level|类目等级'=>'require',
            'moduleid|模块'=>'require',
            'parentid|父级类目id'=>'require',
            'title|类目名称'=>'require',
        ];
        $params = paramForm();
        $this->validate($params,$rule);
        
        $file = request()->file('pic');
        if($file){
            $params['thumb']=$this->uploadToAlyun($file);
        }
        
        $logic = new CategoryLogic();
        $id = $logic->add($params);
        
        if(!$id)$this->error('新增失败');
        
        //关联
        if($params['level']==3&&$params['moduleid']==1){
            
            $rule2 = [
                'type|后台类目数组'=>'require',
            ];
            $this->validate($params,$rule2);
            
            $bindLogic = new CatTypeLogic();
            $post = [];
            if (count($params['type'])<1){
                error('最少关联一个叶子类目');
            }
            foreach ($params['type'] as $type){
                $typeModel = Type::get($type);
                $post[] = ['type_id'=>$type,'category_id'=>$id,'type_title'=>$typeModel['title']];
            }
            
            $ids = $bindLogic->adds($post);
            if(!$ids){
                $logic->delete($id);
                $this->error('新增关联失败,数据回滚');
                return;
            }
            
        }
        
        if($id)$this->success('新增成功','/category/index?moduleid='.$params['moduleid'].'&parentid='.$params['parentid']);

    }
    
    public function edit($id){
        
        $logic = new CategoryLogic();
        $category = $logic->findModel($id);
        $this->assign('types',null);
        if($category->level==3&&$category->moduleid=1){
            $types = $logic->getBindTypeList($id);
            $this->assign('types',$types);
        }
        
        $this->assign('moduleid',$category->moduleid);
        $this->assign('model',$category);
        return $this->fetch();
        
    }
    
    
    public function update($id)
    {
        $logic = new CategoryLogic();
        $category = $logic->findModel($id);
        
        $params = paramForm();
        $file = request()->file('pic');
        if($file){
            $params['thumb']=$this->uploadToAlyun($file);
        }
        
       
        $rt1 = $logic->edit($id,$params);
        
        if(!$rt1)$this->error('未发生变动');
    
        $id = $category['id'];
        //关联
        if($category['level']==3&&$category['moduleid']==1){
            
            $bindLogic = new CatTypeLogic();
            
            $bindLogic->clear($id);//清空之前的记录
   
            
            $post = [];
            if (count($params['type'])<1){
                error('最少关联一个叶子类目');
            }
            foreach ($params['type'] as $type){
//
//                $temp = ['type_id'=>$type,'category_id'=>$id];
//                //排除已经有的记录
                    //已经清空了就不用管了
//                $bindLogic->setValue('condition',$temp);
//                if($bindLogic->prepareDataProvider()){
//                    continue;
//                }
                $typeModel = Type::get($type);
                $post[] = ['type_id'=>$type,'category_id'=>$id,'type_title'=>$typeModel['title']];
               
            }
            
            if(count($post)>0){
                $ids = $bindLogic->adds($post);
                if(!$ids){
                    $logic->del($id);
                    $this->error('更新关联失败,数据回滚');
                    return;
                }
            }
            
            
        }
        
        $this->success('更新成功','index?moduleid='.$category['moduleid'].'&parentid='.$category['parentid']);
        
    }

    /**
     * 删
     * @param $id
     * @return string
     */
    public function delete($id)
    {

        $model = $this->findModel($id);

        $modeulid = $model['moduleid'];
        $parentid = $model['parentid'];
        $rt = $model->delete();
//        var_dump($type);die;
        if ($rt) {
            $this->success("删除成功！", 'index?moduleid='.$modeulid.'&parentid='.$parentid['parentid']);
        } else {
            $this->error("删除失败！");
        }

    }


}